layui.use(['table', 'form','layer','upload'], function () {
    var table = layui.table
        , form = layui.form
        , layer = layui.layer
        ,upload = layui.upload;

    $ = layui.$

    table.render({
        elem: '#video'
        , url: '/Anime/video/getAllVideos'
        , title: "视频表"
        ,toolbar: 'default' //开启工具栏 此处显示默认图标，可以自定义模板
        , cols: [[
            , {type: 'checkbox'}
            , {field: 'id', title: 'ID', width: 100, unresize: true, sort: true}
            , {field: 'uid', title: '用户ID', width: 80}
            , {field: 'videoDesc', title: '视频名称', width: 320,edit:true}
            , {field: 'remark', title: '视频描述', width: 400, unresize: true}
            , {field: 'videoPath', title: '播放', width: 100, templet:function (d) {
                    return "<button type=\"button\" onclick='play(\"" + d.videoPath + "\")' class=\"layui-btn layui-btn-warm layui-btn-sm layui-btn-radius\">点击播放</button>"
                }}
            , {field: 'videoSeconds', title: '视频时长', width: 90, unresize: true}
            , {field: 'coverPath', title: '视频封面', width: 100,templet:function (d) {
                console.log(d.coverPath)
                    return "<img src='.." + d.coverPath + "'>"
                }}
            , {field: 'likeCounts', title: '点赞数', width: 85, unresize: true,edit:true}
            , {field: 'status', title: '视频状态', width: 95, templet: function (d) {
                if(d.status == 1){
                    return "<input type=\"checkbox\" id='status' name=\"status\" value=\"" + d.id + "\" lay-skin=\"switch\" lay-text=\"发布|封禁\" lay-filter=\"statusDemo\" checked>"
                }else {
                    return "<input type=\"checkbox\" id='status' name=\"status\" value=\"" + d.id + "\" lay-skin=\"switch\" lay-text=\"发布|封禁\" lay-filter=\"statusDemo\">"
                }
                }, unresize: true}
            , {field: 'playCounts', title: '播放量', width: 85, unresize: true,edit:true}
            , {field: 'comments', title: '评论数', width: 85, unresize: true,edit:true}
            , {field: 'createTime', title: '创建时间', width: 160, templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>',  unresize: true}
            ,{title:'操作', width: 160, toolbar: '#barDemo'}
        ]]
        , page: true
    });

    //监听状态操作
    form.on('switch(statusDemo)', function (obj) {
        layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
        var id = obj.value
        var check = obj.elem.checked
        var value = check == true?1:0
        var name = this.name
        $.ajax({
            type:'post',
            url:'/Anime/video/update',
            dataType:'json',
            data:{
                'id':id,
                'value':value,
                'name':name
            },
            success:function (res) {
                if(res.code == 0){
                    layer.msg(res.msg)
                }else {
                    layer.msg(res.msg)
                    $("#status").attr("checked")
                }
            }
        })
    });

    //监听行工具条
    table.on('tool(videoTable)', function(obj){
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

        if(layEvent === 'detail'){ //查看
            //do somehing
        } else if(layEvent === 'del'){ //删除
            layer.confirm('真的删除行么', function(index){
                $.ajax({
                    type:'post',
                    url:'/Anime/video/del',
                    dataType:'json',
                    data:{
                        'id':data.id
                    },
                    success:function (res) {
                        if(res.code == 0){
                            layer.msg(res.msg);
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        }else {
                            layer.msg(res.msg)
                        }
                    },
                    error:function () {
                        layer.msg("系统繁忙，请稍后重试！")
                    }
                })
                layer.close(index);
                //向服务端发送删除指令
            });
        }else if (layEvent === 'down') {
            window.location.href = "/Anime/video/down?filename=" + data.videoPath
        }
    });

    //监听单元格编辑
    table.on('edit(videoTable)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
        console.log(obj.value); //得到修改后的值
        console.log(obj.field); //当前编辑的字段名
        console.log(obj.data); //所在行的所有相关数据
        var value = obj.value,
            name = obj.field,
            id = obj.data.id;
        $.ajax({
            type:'post',
            url:'/Anime/video/update',
            dataType:'json',
            data:{
                'value':value,
                'name':name,
                'id':id,
            },
            success:function (res) {
                if(res.code == 0){
                    layer.msg(res.msg)
                }else {
                    layer.msg(res.msg)
                }
            }
        })
    });

    //监听头工具栏操作
    table.on('toolbar(videoTable)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id),
        data = checkStatus.data;
        var ids = new Array();
        for (var i in data){
            ids[i] = data[i].id
        }
        switch(obj.event){
            case 'add':
                layer.open({
                    type:2,
                    title:"添加视频",
                    area:['50%','60%'],
                    content:"/Anime/video/content"
                })
                break;
            case 'delete':
                if(ids.length == 0){
                    layer.msg("请选择至少一行！")
                }else {
                    layer.confirm("真的要删除选中行？",function (index) {
                        $.ajax({
                            type:'post',
                            url:'/Anime/video/delVideos',
                            dataType:'json',
                            data:{
                                "ids":ids
                            },
                            traditional:true,
                            success:function (res) {
                                if(res.code == 0){
                                    layer.msg(res.msg)
                                }else {
                                    layer.msg(res.msg)
                                }
                                table.reload('video',{})
                            },
                            error:function (res) {
                                layer.msg("系统繁忙，请稍后重试！")
                            }
                        })
                        layer.close(index)
                    })
                }
                break;
            case 'update':
                layer.msg('编辑');
                break;
        };
    });

    //监听提交
    form.on('submit(submit)', function(data){
        var index = parent.layer.getFrameIndex(window.name);
        console.log(data.field)
        $.ajax({
            type:'post',
            url:'/Anime/video/addVideo',
            dataType:'json',
            data:data.field,
            success:function (res) {
                layer.msg(res.msg)
                parent.layer.close(index);
                table.reload('video',{})
            },
            error:function (res) {
                layer.msg("系统繁忙，请稍后重试！")
            }

        })
        return false;
    });

    //Search
    $("#searchBtn").on("click",function () {
        var search = $("#searchText").val();
        table.reload('video', {
            url: '/Anime/video/searchName'
            ,where: {
                "value":search
            } //设定异步数据接口的额外参数
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    })
});

function judge(res) {
    if(res.code == 0){
        layer.msg(res.msg)
    }else {
        layer.msg(res.msg)
    }
}

function play(path) {
    var dom = '<video src="../' + path + '" width="100%"  height="100%" controls="controls"></video>'
    layui.use(['layer'],function () {
        var layer = layui.layer;
        layer.open({
            type:1,
            area:['40%','50%'],
            title:'预览',
            content:dom
        })
    })
}